from datetime import datetime
from domain.activity.activity_db import get_activity_list
from domain.activity.activity_db import update_activity_info
from domain.chatroom.chatroom_db import get_chatroom_by_activity
from domain.chatroom.chatroom_db import delete_chatroom

class ActivityAutoFinishHandler:
    @staticmethod
    async def check_and_finish_activities():
        """检查并结束已到结束时间的活动"""
        try:
            # 获取所有进行中的活动
            success, result = await get_activity_list(
                status=[0, 1],  # 0表示未开始，1表示进行中
                page=1,
                page_size=1000
            )
            
            if not success:
                print(f"获取活动列表失败: {result}")
                return

            current_time = datetime.now()
            for activity in result["activities"]:
                # 检查活动是否已到结束时间
                end_time = datetime.strptime(activity["end_time"], "%Y-%m-%d %H:%M:%S")
                if current_time >= end_time:
                    # 更新活动状态为已结束
                    update_success, update_result = await update_activity_info(
                        activity_id=activity["id"],
                        user_id=activity["created_user_id"],
                        activity_data={"status": 2}  # 2表示已结束
                    )
                    
                    if update_success:
                        print(f"活动 {activity['id']} 已自动结束")
                        # 获取并删除聊天室
                        chat_info = await get_chatroom_by_activity(activity["id"])
                        if chat_info[0]:
                            await delete_chatroom(chat_info[1]["id"])
                            print(f"活动 {activity['id']} 的聊天室已删除")
                    else:
                        print(f"结束活动 {activity['id']} 失败: {update_result}")
                        
        except Exception as e:
            print(f"检查活动结束时间时发生错误: {str(e)}")